import React from 'react'
import { Button } from 'antd'
import Moment from 'moment'
import { SchemaForm, Item, Submit, Observer, Layout, FORM_MODE } from '@amazebird/antd-schema-form'

const schema = {
  name: {
    label: '姓名',
    component: Observer({
      watch: '#mode',
      action: (mode) => {
        switch (mode) {
          case FORM_MODE.ADD:return 'Input.Edit'
          case FORM_MODE.MODIFY:return 'Input.Text'
          case FORM_MODE.DETAIL:return 'Input.Text'
        }
      }
    })
  },
  age: {
    label: '年龄',
    component: 'Input'
  },
  sex: {
    label: '性别',
    component: 'Radio',
    options: [{ value: 1, label: '男' }, { value: 0, label: '女' }]
  },
  birthday: {
    label: '出生日期',
    component: 'DatePicker',
    transform: {
      input: (value) => {
        if (value){
          return Moment(value)
        }
      },
      output: (value) => {
        if (value) return value.format('YYYY-MM-DD')
      }
    }
  },
  studyTime: {
    label: '学习时间',
    component: 'RangePicker',
    transform: {
      input: (value) => {
        if (value) {
          const { startTime, endTime } = value
          return [Moment(startTime), Moment(endTime)]
        }
      },
      output: (value) => {
        if (value) {
          const [start, end] = value
          return {
            startTime: start.format('YYYY-MM-DD'),
            endTime: end.format('YYYY-MM-DD')
          }
        }
      }
    }
  }
}

const initData = {
  name: '王大锤',
  age: '12',
  sex: 1,
  birthday: '2021-08-10',
  studyTime: {
    endTime: '2021-12-15',
    startTime: '2021-11-28'
  }
}

function ModeDemo() {
  const form: any = SchemaForm.createForm()
  return (
    <SchemaForm schema={schema} form={form} initialValues={initData}>
      <Item field="name" />
      <Item field="age" />
      <Item field="birthday" />
      <Item field="sex" />
      <Item field="studyTime" />
      <Layout offset={8}>
        <Button onClick={() => form.setState({ mode: FORM_MODE.ADD })}>新增模式</Button>
        <Button onClick={() => form.setState({ mode: FORM_MODE.MODIFY })}>修改模式</Button>
        <Button onClick={() => form.setState({ mode: FORM_MODE.DETAIL })}>详情模式</Button>
        <Submit onFinish={(data) => { console.info(data) }} />
      </Layout>
    </SchemaForm>
  )
}

export default ModeDemo
